package com.mspersonalized.circumscribedAPI.service;

import com.mspersonalized.circumscribedAPI.utils.HttpUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AlyRxfgService {
    @Value("${aly.AppCode.rxfg}")
    private String appcode;

    private String host = "https://perdc.market.alicloudapi.com";
    private String path = "/bodyseg";

    public String rxfg(MultipartFile file) {
        String method = "POST";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("src", convertFileToBase64(file));
        bodys.put("type", "all");

//        System.out.println("ok:\n"+rxfg.getBase64());
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.getEntity().getContent());
            // 访问JSON字段
            String msg = jsonNode.get("msg").asText();
            String status = jsonNode.get("status").asText();

//            System.out.println("status: " + status);
//            System.out.println("msg: " + msg);
            log.info(status+":"+msg);

            //返回响应数据
            return msg;
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "no data";
    }

    public String urlToBase64(String picUrl) throws Exception {
        // 获取图片的 URL
        URL url = new URL(picUrl);

        // 获取图片的输入流
        try (InputStream inputStream = url.openStream()) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            // 创建一个缓冲区
            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从 inputStream 读取到 buffer，直到没有更多数据
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 将输出流的内容转换为 byte 数组，然后转换为 base64
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());

            return base64;
        }
    }

    public String convertFileToBase64(MultipartFile file) {
        try {
            // 读取文件内容到字节数组
            byte[] bytes = file.getBytes();

            // 使用 Base64 编码字节数组
            String base64 = Base64.getEncoder().encodeToString(bytes);

            return base64;
        } catch (IOException e) {
            // 处理异常情况
            e.printStackTrace();
            return null;
        }
    }

}
